package com.hxexp.weixin.mvc.interceptor;

import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.hxexp.weixin.common.config.DeployConfig;
import com.hxexp.weixin.common.web.CookieUtil;
import com.hxexp.weixin.common.web.HttpUtil;
import com.hxexp.weixin.common.zip.ZipUtils;
import com.hxexp.weixin.constant.CookieName;
import com.qq.weixin.constant.APIConstant;
import com.qq.weixin.constant.AppDevConstant;

/**
 * 微信网页授权拦截器
 *
 * <p>
 * 该拦截器的功能是重定向到微信公众平台认证URL获取code参数，通过此参数可以获取用户的openid
 *
 * @author li.jiang
 *
 */
public final class WeixinOauth2Interceptor extends HandlerInterceptorAdapter {
    @Autowired
    private DeployConfig deployConfig;
    /*
     * (non-Javadoc)
     *
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#
     * preHandle(javax.servlet.http.HttpServletRequest,
     * javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie openidCookie = CookieUtil.getCookieByName(request, CookieName.OPENID);
        // 如果保存openid的cookie不存在或已失效，重定向到认证url
        if (openidCookie == null || StringUtils.isEmpty(openidCookie.getValue())) {
            // 已获取code参数不再重定向到认证URL
            if (!StringUtils.isEmpty(request.getParameter("code"))) {
                return super.preHandle(request, response, handler);
            }
            String queryString = HttpUtil.parameterMap2QueryString(request); // 查询参数字符串
            // 获取openid并写入cookie的URL
            String oauth2OpenidURL = String.format("http://%s%s%s", request.getHeader("Host"), request.getContextPath(),
                    APIConstant.OAUTH2_OPENID_URI);

            String returnURL = String.format("http://%s%s", request.getHeader("Host"), request.getRequestURI());
            // 判断查询参数字符串是否存在
            if (!StringUtils.isEmpty(queryString)) {
                // 拼装完整的URL，包括查询参数，认证成功后会跳转回该地址,这里做数据压缩处理是为了防止认证通过后返回原来的页面丢失查询参数
                returnURL = ZipUtils.gzip(String.format("%s?%s", returnURL, queryString));
            } else {
                returnURL = ZipUtils.gzip(returnURL);
            }
            oauth2OpenidURL = String.format("%s?returnURL=%s", oauth2OpenidURL, returnURL);
            oauth2OpenidURL = URLEncoder.encode(oauth2OpenidURL, "UTF-8"); // URL转码:转义特殊字符

            // 重定向到微信网页认证URL，认证通过后返回到原来的页面
            response.sendRedirect(
                    String.format(APIConstant.AUTHORIZE_URL_TEMPLATE, AppDevConstant.getAppId(deployConfig.getDeployEnvironment()), oauth2OpenidURL));

            return false;
        } else {
            return super.preHandle(request, response, handler);
        }
    }

}
